﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ComponentModel;

namespace WcfServiceDemo
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    //[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Service1 : IService1
    {
        //public void NormalFunction(string str)
        //{
        //    IMyContractCallBack callback = OperationContext.Current.GetCallbackChannel<IMyContractCallBack>();
        //    callback.CallBackFunction(str);
        //}

        private static List<string> listDataChat = new List<string>();
        private static Dictionary<string, IClientCallback> IClientCallbackList = new Dictionary<string, IClientCallback>();
        

        public List<string> GetDataChat()
        {
            return listDataChat;
        }

        public void AddText(string str)
        {
            listDataChat.Add(str);

            // Thuc hien ngam refreshData()
            BackgroundWorker _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += BackgroundWorker_DoWork;
            _backgroundWorker.RunWorkerAsync();
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (IClientCallback item in IClientCallbackList.Values)
            {
                item.RefreshData();
            }
        }

        public string RegisterClient()
        {
            IClientCallback iClientCallback = OperationContext.Current.GetCallbackChannel<IClientCallback>();
            string key = Guid.NewGuid().ToString();
            IClientCallbackList.Add(key, iClientCallback);
            return key;
        }

        public void RemoveClient(string keyClientProxy)
        {
            IClientCallbackList.Remove(keyClientProxy);
        }
    }
}
